/**
 * @author lilin
 * @date 2016年3月29日 上午11:43:18
 * @annotation GPS 后台定位服务(采用前台定位服务)
 */
package com.lilin.gps.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.lilin.gps.MainActivity;
import com.lilin.gps.R;
import com.lilin.gps.broadcast.GPSAlarmReceiver;
import com.lilin.gps.utils.DateUtils;

public class GPSService extends Service {
	public static String tag = "GPSService";
	public static final int GPSNOTIFICATIONID = 1001;
	// 轮询时间
	private int cycleTime = 30*1000;
	
	@Override
	public IBinder onBind(Intent arg0) {
		Log.d(tag, "onBind");
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.d(tag, "onCreate");
		// 设置为前台服务
		Notification notification = new Notification(R.drawable.icon, "定位服务",System.currentTimeMillis());
		Intent mIntent = new Intent(this, MainActivity.class);
		// PendingIntent pendIntent = PendingIntent.getActivity(this, 0, mIntent,0);
		// 取消通知点击跳转意图
		notification.setLatestEventInfo(this, "GPS定位服务", "实时获取位置信息", null);
			
		startForeground(GPSNOTIFICATIONID, notification);
		
		
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(tag, "onStartCommand");
		
		// 开启子线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				Log.d(tag, "当前时间 "+DateUtils.getCurrentTime()+"GPS位置上报");
				// 位置上报
				MainActivity.uploadGPS();
			}
		}).start();
		// 初始化定时器,定时发送广播
		initAlarm();
		
		return super.onStartCommand(intent, flags, startId);
	}
	// 定时器管理类
	AlarmManager 	alarmManager;
	// 指定发送的广播接收器
	Intent 			gpsalarmReceiver;
	// 延迟意图
	PendingIntent 	gpsIntent;
	
	private void initAlarm() {
		alarmManager 		= (AlarmManager) getSystemService(ALARM_SERVICE);
		long triggerAtTime 	= SystemClock.elapsedRealtime() + cycleTime;
		gpsalarmReceiver 	= new Intent(this, GPSAlarmReceiver.class);
		gpsIntent 			= PendingIntent.getBroadcast(this, 0, gpsalarmReceiver, 0);
		
		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, gpsIntent);
	}

	@Override
	public void onDestroy() {
		Log.d(tag, "onDestroy");
		super.onDestroy();
		// 关闭定时器
		alarmManager.cancel(gpsIntent);
	}

}
